<template>
	<view class="container">
		<view class="card-wrapper">
			<view class="content-section">
				<view class="content-wrapper">
					<view class="item ">
						<view class="cell flex-row y-center">
							<text class="require">*</text>
							<text class="label">车牌号</text>
							<view class="flex-row y-center right" @click="chooseImage()">
								<u--image :showLoading="true" src="/static/sao.png" width="30rpx"
									height="30rpx"></u--image>
								<text>点击自动识别车牌</text>
							</view>

						</view>
					</view>
					<view class="item">
						<view class="cell flex-row y-center flex1">
							<u--input class="carNo flex-row y-center" v-model="formModel.plate" placeholder="请输入车牌号"
								border="none"></u--input>
							<!-- <text  class="carNo flex-row y-center">{{formModel.plate}}</text> -->
							<button class="custom-style" @click="getCarInfo()">获取车辆信息</button>
						</view>
					</view>
					<view v-if="carInfo">
						<view class="item row-between">
							<view class="cell row-center">
								<text class="label">车主姓名</text>
								<text class="value">{{carInfo.name}}</text>
							</view>
							<view class="cell row-center">
								<text class="label">车辆类型</text>
								<text class="value">{{carInfo.registrationType}}</text>
							</view>
						</view>
						<view class="item">
							<view class="cell flex-row y-center">
								<text class="label">联系电话</text>
								<text class="value">{{$commonUtil.truncateStrReplaceStar(carInfo.moble)}}</text>
							</view>
						</view>
					</view>

				</view>
				<view class="divider row-center">
					<u--image :showLoading="true" src="/static/line.png" width="678rpx" height="4rpx"></u--image>
				</view>
			</view>

			<view class="from-wrapper">
				<u--form errorType="toast" labelPosition="left" labelWidth="150rpx" :model="formModel" :rules="rules"
					ref="uForm">
					<!-- <picker mode="selector" :range="campusList" v-model="campusIndex" range-key="name"
						@change="onPickerChange($event,'campus')">
						<u-form-item label="校区" prop="campusCode" borderBottom>
							<view class="flex-row y-center x-end flex1">
								<text class="input-value">{{campusList[campusIndex].name}}</text>
								<u-icon name="arrow-down-fill" color="#666" size="14"></u-icon>
							</view>
						</u-form-item>
					</picker> -->
					<u-form-item label="校区" prop="campusCode" borderBottom>
						<view class="flex-row y-center x-end flex1">
							<text class="input-value">{{formModel.campusName}}</text>
							<!-- <u-icon name="arrow-down-fill" color="#666" size="14"></u-icon> -->
						</view>
					</u-form-item>
					<u-form-item label="违停地点" prop="location" borderBottom>
						<view class="flex-row y-center x-end flex1">
							<view class="row-center">
								<u--input class=" flex-row y-center " v-model="formModel.location" placeholder="请输入位置"
									border="none"></u--input>
								<!-- <text class="address-btn">获取位置</text>
								<u--image :showLoading="true" src="/static/address.png" width="30rpx"
									height="36rpx"></u--image> -->
							</view>
						</view>
						<!-- <u--input readonly v-model="formModel.location" border="none">
							<template slot="suffix">
								<view class="row-center" @click="getLocation()">
									<text class="address-btn">获取位置</text>
									<u--image :showLoading="true" src="/static/address.png" width="30rpx"
										height="36rpx"></u--image>
								</view>
							</template>
						</u--input> -->
					</u-form-item>
					<!-- <u-form-item labelWidth="200rpx" @click="show = true" label="违停登记时间" prop="violationTime"
						borderBottom>
						<view class="flex-row y-center x-end flex1">
							<text class="input-value">{{formModel.violationTime}}</text>
							<u-icon name="arrow-down-fill" color="#666" size="14"></u-icon>
						</view>
					</u-form-item> -->
					<u-form-item label="违停描述" labelPosition="top" prop="description" borderBottom>
						<view style="position: relative;width: 100%;">
							<u-textarea style="padding-right: 30rpx;" autoHeight v-model="formModel.description"
								:maxlength="500" placeholder="请输入违停描述" border="none"></u-textarea>
							<view style="position: absolute;right: 0;top: 16rpx;">
								<picker mode="selector" :range="descriptionList" v-model="descriptionIndex"
									range-key="dictValue" @change="onPickerChange($event,'description')">
									<u-icon name="arrow-down-fill" color="#666" size="14"></u-icon>
								</picker>
							</view>
						</view>
					</u-form-item>
					<u-form-item label=" " labelPosition="top" prop="password" borderBottom>
						<view class="mt16">
							<u-upload :compressed="true" :fileList="formModel.violationPhotos" @afterRead="afterRead"
								@delete="deletePic" multiple :maxCount="10">
								<image src="/static/upload.png" mode="aspectFill" style="width: 200rpx;height: 152rpx;">
								</image>
							</u-upload>
						</view>
					</u-form-item>

				</u--form>
			</view>
		</view>
		<u-button class="submit-style" text="提交" @click="onSubmit"></u-button>
		<!-- 时间插件 -->
		<u-datetime-picker @cancel="show=false" @confirm="confirmTime" :show="show" v-model="timeValue"
			mode="datetime"></u-datetime-picker>
	</view>
</template>

<script>
	import {
		getWXAccessTokenApi,
		ocrPlatenumApi,
		getInfoApi
	} from '@/apis/common.js';

	import {
		registerViolationApi,
		getVehicleInfoByPlateNumberApi,
		illegalParkingDescriptionApi
	} from '@/apis/disposal.js';

	export default {
		data() {
			return {
				campusList: [{
					name: '华西',
					code: 1
				}, {
					name: '望江',
					code: 2
				}, {
					name: ' 江安',
					code: 3
				}],
				descriptionList: [],
				descriptionIndex: 0,
				campusIndex: 0,
				show: false,
				timeValue: Number(new Date()),
				carInfo: null,
				isSubmit: true,
				formModel: {
					campusCode: "", //校区code
					campusName: "", //校区code
					location: "", //位置
					// violationTime: this.getCurrentFormattedTime(), //登记时间
					description: "", //违章描述
					plate: "", //车牌号
					violationPhotos: [] //照片
				},
				rules: {
					'violationTime': {
						type: 'string',
						required: false,
						message: '请选择时间',
						trigger: ['blur', 'change']
					},
					'violationPhotos': {
						type: 'array',
						min: 1,
						required: true,
						message: '请上传图片',
						trigger: ['change', 'blur']
					},
					'description': {
						type: 'string',
						required: true,
						message: '请填写描述',
						trigger: ['blur', 'change']
					},
				},
			}
		},

		created() {
			this.getInfo();
			this.illegalParkingDescription();

		},
		// onReady() {
		// 	//如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
		// 	this.$refs.uForm.setRules(this.rules)
		// },
		methods: {
			chooseImage() {
				uni.chooseImage({
					quality: 50,
					success: async (chooseImageRes) => {
						const tempFilePaths = chooseImageRes.tempFilePaths;
						uni.showLoading({
							title: '识别中',
							mask: true
						})
						const result = await this.uploadFilePromise(tempFilePaths[0]);
						this.getCarNum(result)
						console.log(result, 'result')
					}
				});
			},
			resetModel() {
				this.formModel = {
					campusCode: '', //校区code
					location: "", //位置
					violationTime: this.getCurrentFormattedTime(), //登记时间
					description: this.descriptionList[0].dictValue, //违章描述
					plate: "", //车牌号
					violationPhotos: [] //照片
				}
			},
			async getInfo() {
				try {
					let resp = await getInfoApi();
					this.formModel.campusCode = resp.campus || '';
					this.campusIndex = this.campusList.findIndex((val) => {
						return val.code == this.formModel.campusCode
					});
					this.campusIndex = this.campusIndex || 0;
					this.campusIndex = this.formModel.campusCode - 1 || 0;
					this.formModel.campusName = this.campusList[this.campusIndex].name;
				} catch (e) {
					console.log(`获取用户信息${e.message}`, 'background:orange')
				}
			},
			getCurrentFormattedTime() {
				// 创建一个新的 Date 对象（代表当前日期和时间）
				var now = new Date();
				// 获取各个部分
				var year = now.getFullYear();
				var month = now.getMonth() + 1; // JavaScript的月份从0开始，所以我们需要将结果加1
				var day = now.getDate();
				var hours = now.getHours();
				var minutes = now.getMinutes();
				var seconds = now.getSeconds();

				// 将月份、日期、小时、分钟和秒数格式化为两位数
				month = month < 10 ? '0' + month : month;
				day = day < 10 ? '0' + day : day;
				hours = hours < 10 ? '0' + hours : hours;
				minutes = minutes < 10 ? '0' + minutes : minutes;
				seconds = seconds < 10 ? '0' + seconds : seconds;
				// 拼接出一个格式为 "YYYY-MM-DD HH:MM:SS" 的字符串
				var formattedTime = year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;
				return formattedTime;
			},
			// 获取车牌号
			async getCarNum(img_url) {
				try {
					let resp = await getWXAccessTokenApi();
					// let carResp = await ocrPlatenumApi(encodeURIComponent(img_url), resp.access_token);
					let params = {
						imageUrl: img_url,
						accessToken: resp.access_token
					}
					let carResp = await ocrPlatenumApi(params);
					this.formModel.plate = carResp.number;

				} catch (e) {
					console.log(`%获取车牌号${e.message}`, 'background:orange')
				} finally {
					uni.hideLoading();
				}
			},
			// 获取车辆信息
			async getCarInfo() {
				if (!this.formModel.plate || !this.isValidPlateNumber(this.formModel.plate)) {
					uni.showToast({
						title: '请扫码车牌获取车牌号,或者输入正确的车辆号码',
						icon: 'none'
					})
					return;
				}
				let resp = await getVehicleInfoByPlateNumberApi({
					plateNumber: this.formModel.plate
				})
				this.carInfo = resp.data || null;
			},
			formatterTime(timestamp) {
				const date = new Date(timestamp);
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				const hour = String(date.getHours()).padStart(2, '0');
				const minutes = String(date.getMinutes()).padStart(2, '0');
				const seconds = String(date.getSeconds()).padStart(2, '0');
				const formattedDate = `${year}-${month}-${day} ${hour}:${minutes}:${seconds}`;
				console.log(formattedDate, 'formattedDate');
				return formattedDate;
			},
			// 获取位置
			getLocation() {
				console.log('获取位置')
				uni.getLocation({
					success: (res) => {
						// 已测试  可以获取到经纬度
						console.log(res, 'res--')
						// uni.showToast({
						// 	title: `${res.longitude}`,
						// 	icon: 'none',
						// 	duration: 10000000000
						// })
					},
					fail: (err) => {
						console.log("getLocation调用失败", err);
					},
				});
			},
			//数据字典
			async illegalParkingDescription() {
				try {
					let resp = await illegalParkingDescriptionApi();
					this.descriptionList = resp.data;
					this.formModel.description = this.descriptionList[0].dictValue;
				} catch (e) {
					console.log(`%c数据字典${e.message}`, 'background:orange')
				} finally {

				}
			},
			// 选择时间
			confirmTime(e) {
				console.log(e, 'eee')
				this.show = false;
				this.formModel.violationTime = this.formatterTime(e.value);
			},
			onPickerChange(e, source) {
				let index = `${source}Index`;
				this[index] = e.detail.value;
				if (source === 'campus') {
					this.formModel.campusCode = this.campusList[this.campusIndex].code;
				} else {
					this.formModel.description = this.descriptionList[this.descriptionIndex].dictValue;
				}
			},
			// 删除图片
			deletePic(event) {
				this.formModel.violationPhotos.splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this.formModel.violationPhotos.length
				this.isSubmit = false;
				let len = 0;
				lists.map((item) => {
					this.formModel.violationPhotos.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					console.log(result, 'result')
					let item = this.formModel.violationPhotos[fileListLen]
					this.formModel.violationPhotos.splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++;
					len++;
					if (len == lists.length) {
						this.isSubmit = true;
					}
				}

				console.log(fileListLen, 'fileListLen')
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: `${this.$config.baseUrl}/common/upload`, // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						header: {
							Authorization: uni.getStorageSync('token')
						},
						formData: {},
						success: (res) => {
							let resp = JSON.parse(res.data)
							console.log(resp, 'res---')
							if (resp.code == 401) {
								this.$commonUtil.redirectTo('/pages/login/login', {}, 'reLanch')
							}
							if (resp.code == 200) {
								setTimeout(() => {
									resolve(resp.url)
								}, 1000)
							}
						},
						fail: (err) => {
							console.log(err, 'err')
						}
					});
				})
			},

			// 定义函数checkVehicleNumber，输入参数车牌号
			isValidPlateNumber(plateNumber) {
				var regNewEnergy = /^[\u4e00-\u9fa5]{1}[A-Za-z]{1}[A-HJ-NP-Z0-9]{6}$/;
				var reg = /^[\u4e00-\u9fa5]{1}[A-Z]{1}[A-Z0-9]{5}$/;
				// 先检查是否为传统车牌号
				if (reg.test(plateNumber)) {
					return true
				}
				// 再检查是否为新能源车牌号
				if (regNewEnergy.test(plateNumber)) {
					return true; // 是合法的新能源车牌号
				}
				return false; // 不符合任何一种车牌号格式
			},
			//提交
			onSubmit() {
				if (!this.formModel.plate || !this.isValidPlateNumber(this.formModel.plate)) {
					uni.showToast({
						title: '请扫码车牌获取车辆信息,或者输入正确的车辆号码',
						icon: 'none'
					})
					return;
				}
				if (this.formModel.violationPhotos?.length == 0) {
					uni.showToast({
						title: '请上传图片',
						icon: 'none'
					})
					return;
				}
				if (!this.formModel.location) {
					uni.showToast({
						title: '请输入位置'
					})
					return;
				}
				this.$refs.uForm.validate().then((res) => {
					this.confirmSave();
				}).catch(errors => {
					console.log(errors, 'errors')
				})


			},

			async confirmSave() {
				if (!this.isSubmit) {
					uni.showToast({
						title: '图片还在上传中，请稍后提交',
						mask: true,
						icon: 'none'
					})
					return;
				}
				uni.showLoading({
					title: '提交中',
					mask: true
				})
				try {
					let params = JSON.parse(JSON.stringify(this.formModel));
					if (params.violationPhotos?.length > 0) {
						let violationPhotos = params.violationPhotos;
						let img = []
						violationPhotos.map((val) => {
							img.push(val.url)
						})
						params.violationPhotos = img.join(',')
					} else {
						params.violationPhotos = null
					}
					let resp = await registerViolationApi(params);
					uni.showModal({
						title: '登记信息提交成功，是否继续提交？',
						success: (res) => {
							if (res.confirm) {
								this.resetModel();
							} else {
								uni.navigateBack()
							}
						}
					})
				} catch (e) {
					console.log(`%提交违停记录,${e.message},'background:orange'`)
				} finally {
					uni.hideLoading()
				}
			}
		}
	}
</script>

<style scoped lang="scss">
	.container {
		background-color: #fff;
		padding: 0 30rpx;
		padding-top: 20rpx;

		.card-wrapper {
			background: #FFFFFF;
			box-shadow: 0rpx 0rpx 9rpx 4rpx #E1DEDE;
			border-radius: 9rpx;

			.content-section {
				position: relative;

				.divider {
					position: absolute;
					bottom: 0;
					left: 0;
					width: 100%;
					// border: 2rpx dashed #3B67A5;
				}
			}
		}

		.submit-style {
			background-color: #3B67A5;
			font-weight: 400;
			font-size: 28rpx;
			color: #FFFFFF;
			border-radius: 15rpx;
			margin-top: 40rpx;
		}

		.content-wrapper {
			padding: 0 30rpx;

			.item {
				height: 80rpx;
				display: flex;
				align-items: center;



				.cell {
					font-size: 28rpx;
					height: 100%;

					.carNo {
						border-bottom: 1rpx solid #f5f5f5;
						width: 200rpx;
						height: 100%;
						line-height: 100%;
						font-weight: bold;
						color: #3B67A5;
						font-size: 34rpx;
					}

					.label {
						font-size: 28rpx;
						color: #707070;
						margin-right: 10rpx;
					}

					.value {
						font-size: 28rpx;
						color: #333;
						margin-right: 10rpx;
					}

					.require {
						font-size: 28rpx;
						color: #E30F0F;
					}

					.right {
						margin-left: 30rpx;
						color: #3B67A5;
						font-size: 28rpx;

						text {
							margin-left: 10rpx;
						}
					}
				}

				.custom-style {
					width: 167rpx;
					border-radius: 25rpx;
					border: 2rpx solid #E98E23;
					opacity: 0.7;
					font-weight: 400;
					font-size: 23rpx;
					color: #E98E23;
					margin-left: 30rpx;
				}
			}
		}

		.from-wrapper {
			padding: 0 30rpx;

			.input-value {
				font-size: 14px;
				color: #303133;
			}



			/deep/.u-input__content__field-wrapper__field {
				text-align: right !important;
			}

			/deep/.u-textarea {
				padding: 0;
				padding-top: 10rpx;
			}

			.address-btn {
				font-size: 26rpx;
				color: #3B67A5;
				margin-right: 10rpx;
				margin-left: 10rpx;
			}
		}
	}
</style>